function _onClickJobOrderFollowupSaveBtn(){
	
	var formObj = $("form:first");
	formObj.validate();
	
    if(formObj.valid()){
    	if(confirm("هل تريد عرض تقرير أمر العمل ؟")){
	    	formObj.append("<input type='hidden' name='saveThenReturn' value='1' />");
	    	formObj.append("<input type='hidden' name='showJobOrderReport' value='1' />");
	    	formObj.prop("target", "_blank");
	    	//alert("سيتم عرض تقرير أمر العمل بعد الحفظ لتتمكن من طباعته أو حفظ نسخة إلكترونية منه");
	    	formObj.submit();
	    	setTimeout(function(){window.location.href = "FollowupJobOrderSearch"},3000);
    	}else{
    		formObj.submit();
    	}
    	//return true;
    }	
    
    //return false;
}

function setOtherMonthsValues(srcObj) {
	var m1 = parseInt($(srcObj).val());
	var visitNO = parseInt($('input:radio[name="pmAnnualVisitsNo"]:checked').val());
	// alert("m1 : " + m1);
	// alert("type : " + type);
	var nextVal = m1;
	
	$("select.weqa2eya_months").slice(1, visitNO).each(function(index) {
		if(m1 === parseInt(m1, 10)){// check if m1 is integer
			nextVal += 12 / visitNO;
			if (nextVal > 12)
				nextVal = nextVal % 12;
	
			$(this).val(nextVal);
		}else{
			$(this).prop('selectedIndex',0);
		}
	});
	 
}

function _onSubmitDeviceSearchForm() {
	if ($("#deviceCode").val().trim() == ""
			&& $("#deviceSerial").val().trim() == "") {
		alert("من فضلك أدخل قيم لإتمام عملية البحث");
		return false;
	}
	return true;
}

function _onSubmitJobOrderSearchForm() {
	if ($("#jobOrderNo").val().trim() == ""
			&& $("#deviceCode").val().trim() == ""
			&& $("#deviceSerial").val().trim() == "") {
		alert("من فضلك أدخل قيم لإتمام عملية البحث");
		return false;
	}
	return true;
}

function _onSubmitJobOrderInquiryForm(){
	if ($("#jobOrderNo").val().trim() == "") {
		alert("من فضلك أدخل رقم أمر العمل");
		return false;
    }
    return true;
}


function _onSubmitSPCategorySearchForm() {
	if ($("#code").val().trim() == "") {
		alert("من فضلك أدخل الكود لإتمام عملية البحث");
		return false;
	}
	return true;
}

function getPPMVisit() {

	var subcontractor = $("#subcontractor").val();
	var selectedMonth = $("#visitMonth").val();
	var selectedYear = $("#visitYear").val();
	var deviceId = $("#deviceId").val();
	var dest = $("#dest").val();

	// if (selectedMonth > 0 && selectedYear > 0).prop("selectedIndex")

	if ($("#visitMonth").prop("selectedIndex") != 0
			&& $("#visitYear").prop("selectedIndex") != 0)
		$("#content_container").load("PPMVisitDisplay", {
			visitMonth : selectedMonth,
			visitYear : selectedYear,
			deviceId : deviceId,
			subcontractor: subcontractor,
			dest : dest
		}, function() {
			initPage()
		});

}

function initPage() {

	$("body").prop("class", "pure-skin-mine");
	$("form").prop("class", "pure-form");
	$("table.layout_grid tr:last > td").each(
     function(){
		if($(this).find("input#biomedapp_return_btn").length > 0)
		   $(this).css({"padding-top":"30px","padding-right":"50px"});		        
	});
 

	// init calendar elements
	$(".caldr").datepicker({
		dateFormat : 'dd/mm/yy',
		changeMonth : true,
		changeYear : true,
		yearRange : "-30:+5"
	});

	// init file upload elements
	initFileInputElements();

	// $("select:not(.auto_off)").each(function(){alert("init :: "+this.name + "
	// :: "+$(this).find("option[selected='selected']").size() )})
	// add default option to dropdown lists
	$("select:not(.auto_off)")
			.prepend("<option value=''>من فضلك اختر</option>").each(function() {
				if ($(this).find("option[selected='selected']").size() == 0)
					this.selectedIndex = 0
			});
	$("select.auto_add_all").prepend("<option value='0'>الكل</option>").each(
			function() {
				if ($(this).find("option[selected='selected']").size() == 0)
					this.selectedIndex = 0
			});

	// style buttons with pure framework
	$("input[type='button']").addClass("pure-button");
	$("input[type='submit']").addClass("pure-button pure-button-primary");

	// add margin between horizontal radio group
	$("input[type='radio']").css("margin-left", "2px");
	$("input[type='radio']").next().css("margin-right", "15px");

	// special css to handle the category radios properly
	$("input[type='radio'][name='category']").css("margin-right", "2px");
	$("input[type='radio'][name='category']").next().css("margin-left", "15px");

	// add margin between horizontal checkbox group
	$("input[type='checkbox']").css("margin-left", "2px");
	$("input[type='checkbox']").next().css("margin-right", "15px");

	appendCommonQueryStrToReportsMenuItems();

	$("form").attr('novalidate', 'novalidate');
	$("form").validate({

						// ignore: ":hidden:not(input:file)", // to allow hidden
						// fields to validated

						errorPlacement : function(error, element) { // to adjust
							// the radio and checkbox group msg placement
							if ($(element).is("input:file")) {
								if (element.closest("label").parent().find("span[class='requiredField']").length > 0)
									error.insertAfter(element.closest("label").parent().find("span[class='requiredField']"));
								else
									error.insertAfter(element.closest("label"))
							} else
									error.appendTo(element.parent());	
						}
					// debug:false,
					// focusInvalid: false,
					// onfocusout: false
					// onkeyup: false
					// rules:{
					// plannedStartDate: {
					// required:true,
					// dpDate:true,
					// dpCompareDate: ['before', '#plannedEndDate']
					// },
					// plannedEndDate:{
					// required:true,
					// dpDate:true,
					// dpCompareDate: ['after', '#plannedStartDate']
					// }
					//			  
					// }
					});

	initRequiredFields();

	// $("form select[selectrequired]").each((function(){$(this).rules("add",
	// {selectrequired: true})}))
	// markAsRequired("form *[required]");
}

function initNotification(cPath) {
	// init the job order notifications socket
	/*
	 * var eventSource = new EventSource(cPath +
	 * "/JobOrderNotificationsEmitter"); eventSource.onmessage = function(event) {
	 * $("#job_order_notification_ph").html(event.data); //alert(event.data);
	 */
	// }
}

function appendCommonQueryStrToReportsMenuItems() {

	// $("li.reports_menu_items > ul > li > a").each(
	$("#dhtmlgoodies_slidedown_menu > ul > li > ul a").each(
	//$("#dhtmlgoodies_slidedown_menu a").each(
			function() {

				// initially equal to the original href
				var newHref = $(this).prop("href");

				if (newHref.indexOf("purpose=") == -1) {
					newHref += ((newHref.indexOf("?") == -1) ? "?" : "&")
							+ "purpose=" + encodeURIComponent($(this).html());
					$(this).prop("href", newHref);
				}
			});

	// add report flag
	$("li.reports_menu_items > ul > li > a").each(function() {

		if($(this).attr('target') == '_blank')
		    $(this).click(function(){returnToWelcomePage()});
		
		// initially equal to the original href
		var newHref = $(this).prop("href");

		if (newHref.indexOf("report=") == -1) {
			newHref += ((newHref.indexOf("?") == -1) ? "?" : "&") + "report=1";
			$(this).prop("href", newHref);
		}
	});
}

function returnToWelcomePage(){
	window.location.href = $("#home_lnk").attr("href");
}

// init the notifications websocket
var appServerUrl = "ws://"+appServerIP + appContext;
var jobOrderWsCon;

function connectToJobOrderNotifier(siteId) {
	var url = appServerUrl + "/JobOrdersNotifier";
	if(siteId && siteId != 0)
		url += "?siteId=" + siteId;
	
	jobOrderWsCon = new WebSocket(url);

	jobOrderWsCon.onopen = function() {
		console.log('WebSocket connection has been opened');
	}

	jobOrderWsCon.onclose = function() {
		console.log('WebSocket connection has been closed');
	}

	jobOrderWsCon.onerror = function(error) {
		console.log('WebSocket connection has error detected: ' + error);
	}

	jobOrderWsCon.onmessage = function(event) {
		$("jo_notifications_ph").remove();
		var data = event.data;
		$("#notifications_Container").prepend(event.data);
	}
}

var spInventoryWsCon;

function connectToSPInventoryNotifier(siteId) {
	var url = appServerUrl + "/SPInventoryNotifier";
	if(siteId && siteId != 0)
		url += "?siteId=" + siteId;
	
	spInventoryWsCon = new WebSocket(url);

	spInventoryWsCon.onopen = function() {
		console.log('WebSocket connection has been opened');
	}

	spInventoryWsCon.onclose = function() {
		console.log('WebSocket connection has been closed');
	}

	spInventoryWsCon.onerror = function(error) {
		console.log('WebSocket connection has error detected: ' + error);
	}

	spInventoryWsCon.onmessage = function(event) {
		$("sp_notifications_ph").remove();
		var data = event.data;
		$("#notifications_Container").append(event.data);
	}
}

function addValidationRuleForSpCatDuplication() {
	$("input[name='code']").rules("add", {
		remote : {
			url : "CheckSPCategoryDuplication",
			data : {
				code : function() {
					return $("#code").val()
				},
				spCatId : function() {
					if ($("#spCatId").length)
						return $("#spCatId").val();
					return "0"
				}
			}
		}
	});
}

function activateNotificationStopperCookie(obj, cookieName) {
	$(obj).closest("div").remove();
	$.cookie(cookieName, "1");
}

function closeWindow() {
	window.open('','_self','');
	window.close();
	//if (window.opener != null && !window.opener.closed) {
		//alert("parent exists");
		//window.close();
	//} else {
		//window.history.back();
	//}
}